<template>
  <van-nav-bar
    title="标题"
    left-text="返回"
    right-text="按钮"
    left-arrow
    @click-left="goback"
  />
  <van-checkbox-group v-model="result" @change="groupChange">
    <van-card
      v-for="item in carList"
      :key="item.title"
      :num="item.num"
      :price="item.price"
      :title="item.title"
      
    >
    <template #thumb>
      <van-checkbox checked-color="#fcaf17" :name="item.title"></van-checkbox>
      <img :src="item.pic" width="100">
    </template>
      <template #desc>     
      </template>
    </van-card>
  </van-checkbox-group>
  <van-submit-bar
    button-color="linear-gradient(to right, #ffc20e, #e0861a)"
    :price="countPrice"
    button-text="结算订单"
    @submit="onSubmit"
  >
    <van-checkbox v-model="checked" checked-color="#fcaf17" @click="choseAll"
      >全选</van-checkbox
    >
  </van-submit-bar>
</template>

<script>
import { computed, onMounted, reactive, toRefs } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { Toast } from "vant";
export default {
  props: ["carList"],
  setup() {
    const router = useRouter();
    const store = useStore();
    let data = reactive({
      result: [],
      checked: true,
    });
    const goback = () => {
      router.go(-1);
    };
    const updata=()=>{
        return carList.value.filter((item)=>
            data.result.includes(item.title)
        )
    }
    const onSubmit = () => {
        if(data.result.length!=0){
            store.commit("countAbout/PAY",updata())
            router.push('./createorder')
        }
        else{
            Toast.fail('请选择商品')
        }
    }
    const carList = computed(() => {
      return store.state.countAbout.carList;
    });
    const init = () => {
      data.result = carList.value.map((item) => item.title);
    };
    const choseAll = () => {
      if (data.result.length !== carList.value.length) {
        init();
      } else {
        data.result = [];
      }
    };
    const groupChange=(result)=>{
       if(result.length== carList.value.length){
        data.checked=true
       } 
       else{
        data.checked=false
       }
       data.result=result
    }
    const countPrice=computed(()=>{
        let countList=carList.value.filter((item)=>
            data.result.includes(item.title)
        )
        let num=0
        countList.forEach((item)=> {
            num+=item.num*item.price
        });
        return num*100
    })
    onMounted(() => {
      init();
    });
    return {
      onSubmit,
      choseAll,
      groupChange,
      ...toRefs(data),
      countPrice,
      goback,  
    };
  },
};
</script>

<style>
</style>